/**
 * Copyright (c) 2011-2016, Eason Pan(pylxyhome@vip.qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jcbase.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.jcbase.core.auth.anno.RequiresPermissions;
import com.jcbase.core.auth.interceptor.AuthorityInterceptor;
import com.jcbase.core.auth.interceptor.SysLogInterceptor;
import com.jcbase.core.util.IWebUtils;
import com.jcbase.core.util.MyDigestUtils;
import com.jcbase.core.view.InvokeResult;
import com.jcbase.model.SysLoginRecord;
import com.jcbase.model.SysRes;
import com.jcbase.model.SysUser;
import com.jcbase.model.SysUserRole;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;

/**
 * 首页、登陆、登出
 * 
 * @author eason
 */
@Clear(SysLogInterceptor.class)
@RequiresPermissions(value = { "/" })
public class IndexController extends Controller
{

	public void index()
	{
		if (IWebUtils.getCurrentSysUser(getRequest()) == null)
		{
			this.setAttr("codeIs", PropKit.get("codeIsValidate"));
			// this.setAttr("codeIs", "true");
			render("login.jsp");
		}
		else
		{
			SysUser sysUser = IWebUtils.getCurrentSysUser(getRequest());
			List<SysUserRole> sysUserRole = SysUserRole.me
					.find("select * from sys_user_role where user_id = " + sysUser.getId());
			String roleId = "";
			for (SysUserRole sysUserRole2 : sysUserRole)
			{
				roleId = roleId + sysUserRole2.getRoleId();
			}
			this.setAttr("roleId", roleId);
			render("index.jsp");
		}
	}

	public void home()
	{
		render("home.jsp");
	}

	@Clear(AuthorityInterceptor.class)
	public void login()
	{
		this.setAttr("codeIs", PropKit.get("codeIsValidate"));
		this.setAttr("url", this.getPara("url"));
		render("login.jsp");
	}

	@Before(SysLogInterceptor.class)
	@Clear(AuthorityInterceptor.class)
	public void dologin()
	{
		if ("true".equals(PropKit.get("codeIsValidate")))
		{
			String imageCode = this.getPara("imageCode");
			if (StrKit.notBlank(imageCode))
			{
				String imageCodeSession = (String) this.getSessionAttr("imageCode");
				if (!imageCodeSession.toLowerCase().equals(imageCode.trim().toLowerCase()))
				{
					this.renderJson(InvokeResult.failure("验证码输入有误"));
					return;
				}
			}
			else
			{
				this.renderJson(InvokeResult.failure("请输入验证码"));
				return;
			}
		}
		SysUser sysUser = SysUser.me.getByName(this.getPara("username"));
		if (sysUser == null)
		{
			this.renderJson(InvokeResult.failure("用户不存在"));
			return;
		}
		if (SysLoginRecord.dao.hasOverLoginErrTimes(sysUser.getId()))
		{
			this.renderJson(InvokeResult.failure("今天连续输入密码错误次数超过5次"));
			return;
		}
		if (!sysUser.getPwd().equals(MyDigestUtils.shaDigestForPasswrod(this.getPara("password"))))
		{
			SysLoginRecord.dao.saveSysLoginRecord(sysUser.getId(), 0);
			this.renderJson(InvokeResult.failure("用户密码输入有误"));
			return;
		}
		if (sysUser.getInt("status") == 2)
		{
			this.renderJson(InvokeResult.failure("用户被冻结，请联系管理员"));
			return;
		}
		Integer autoLogin = this.getParaToInt("autoLogin", 0);
		IWebUtils.setCurrentLoginSysUser(this.getResponse(), this.getSession(), sysUser, autoLogin);
		SysLoginRecord.dao.saveSysLoginRecord(sysUser.getId(), 1);
		render("index.jsp");
		this.renderJson(InvokeResult.success());
	}

	public void getMenu()
	{
		SysUser sysUser = IWebUtils.getCurrentSysUser(getRequest());
		List<SysRes> allMenuList = SysRes.getSysResList(sysUser.getId(), 1);
		List<HashMap<String, Object>> menuList = new ArrayList<HashMap<String, Object>>();
		for (SysRes sysRes : allMenuList)
		{
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("create_time", "");
			map.put("icon", sysRes.getIconCls());
			map.put("id", sysRes.getId());
			map.put("menu_name", sysRes.getName());
			map.put("menu_url", sysRes.getUrl());
			map.put("order_num", sysRes.getSeq());
			if (sysRes.getPid() == null)
			{
				map.put("parent_id", 0);
			}
			else
			{
				map.put("parent_id", sysRes.getPid());
			}

			menuList.add(map);
		}
		this.renderJson(menuList);
	}

	public void getAllMenu()
	{
		List<SysRes> allMenuList = SysRes.me.getAllList();
		List<HashMap<String, Object>> menuList = new ArrayList<HashMap<String, Object>>();
		for (SysRes sysRes : allMenuList)
		{
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("create_time", "");
			map.put("icon", sysRes.getIconCls());

			map.put("menu_url", sysRes.getUrl());
			map.put("order_num", sysRes.getSeq());
			map.put("id", sysRes.getId());
			map.put("menu_name", sysRes.getName());
			if (sysRes.getPid() == null)
			{
				map.put("parent_id", 0);
			}
			else
			{
				map.put("parent_id", sysRes.getPid());
			}

			menuList.add(map);
		}
		this.renderJson(menuList);
	}

	@Before(SysLogInterceptor.class)
	public void loginOut()
	{
		IWebUtils.removeCurrentSysUser(getRequest(), getResponse());
		this.redirect("/login");
	}

	public void pwdSetting()
	{
		try
		{
			SysUser sysUser = IWebUtils.getCurrentSysUser(getRequest());
			this.setAttr("sysUser", sysUser);
			render("sys/pwd_setting.jsp");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

	}

	@Before(SysLogInterceptor.class)
	public void savePwdUpdate()
	{
		String oldPwd = MyDigestUtils.shaDigestForPasswrod(getPara("oldPwd"));
		String newPwd = MyDigestUtils.shaDigestForPasswrod(getPara("newPwd"));
		try
		{
			SysUser sysUser = IWebUtils.getCurrentSysUser(getRequest());
			if (!sysUser.get("pwd").equals(oldPwd))
			{
				this.renderJson(InvokeResult.failure(-3, "旧密码不正确"));
			}
			else
			{
				InvokeResult result = SysUser.me.savePwdUpdate(sysUser.getInt("id"), newPwd);
				this.renderJson(result);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

	}
}
